/*
 * Copyright 2014 Cungmua, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cungmua.vn.kiosk.activity;

import java.text.BreakIterator;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONObject;

import com.androidquery.callback.ImageOptions;

import android.R.integer;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.audiofx.Visualizer.OnDataCaptureListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import cungmua.vn.kiosk.AbstractActivity;
import cungmua.vn.kiosk.R;
import cungmua.vn.kiosk.db.DatabaseHandler;
import cungmua.vn.kiosk.handle.DonHangDetailHandler;
import cungmua.vn.kiosk.handle.ServiceHandler;
import cungmua.vn.kiosk.model.DonHang;
import cungmua.vn.kiosk.model.NhanVien;
import cungmua.vn.kiosk.model.SKU;
import cungmua.vn.kiosk.network.CallServices;
import cungmua.vn.kiosk.tabs.BadgeTabManager;
import cungmua.vn.kiosk.tabs.TabGroupActivity;
import cungmua.vn.kiosk.utils.Utils;
import cungmua.vn.kiosk.utils.WriteLog;

/**
 * @author kelvin.nguyen
 * 
 */
public class DonHangDetailActivity extends AbstractActivity implements
		OnDateChangedListener {
	private ProgressDialog dialog;
	private TextView txt_tong_can_thu;
	private TextView txt_create_date;
	private TextView txt_client_name;
	private TextView txt_client_phone;
	private TextView txt_client_address;
	private TextView txt_comments;
	private TextView txt_ma_dh;
	private TableRow row;
	private TableLayout tblDonHang;
	private DatabaseHandler db;
	private NhanVien nhanvien;
	private DonHang donhang;
	private double total_canthu = 0;
	private int option = 1;
	private String shipDate;
	private String datePart = "1";

	/**
	 * This integer will uniquely define the dialog to be used for displaying
	 * time picker.
	 */
	static final int TIME_DIALOG_ID = 0;
	private int pDay;
	private int pMonth;
	private int pYear;

	final CharSequence myList[] = { "Sáng", "Chiều", "Tối" };

	public DatePickerDialog myDialog;
	DatePickerDialog datePickerDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_donhang_chitiet);
		db = new DatabaseHandler(self);
		nhanvien = db.getAllNhanviens().get(0);
		// define resource xml
		initView();

		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			donhang = bundle.getParcelable(DONHANG);
			// new getOrderDetail().execute();

			if (donhang.getNote() == null) {
				findViewById(R.id.ll_comment).setVisibility(GONE);
			}

			String buildingName = donhang.getBuildingName() == null ? ""
					: donhang.getBuildingName();

			// set data for xml resource
			txt_client_name.setText(donhang.getCustomerName());
			txt_client_phone.setText(donhang.getPhone());
			txt_client_address.setText(donhang.getAddress() + ", "
					+ buildingName);
			txt_comments.setText(donhang.getNote());
			txt_tong_can_thu.setText(Utils.priceWithoutDecimal(donhang
					.getTotalMoney()) + "đ");
			total_canthu += donhang.getTotalMoney();
			txt_create_date
					.setText(Utils.formateDate(donhang.getTimeCreated()));
			txt_ma_dh.setText("DH " + donhang.getOrderId());

			// check customer isVip ?
			int isShow = donhang.getIsVip() == 0 ? View.GONE : View.VISIBLE;
			findViewById(R.id.iv_vip).setVisibility(isShow);

			int sl = db.getAllSKUByOrderId(donhang.getOrderId()).size();

			for (SKU sku : db.getAllSKUByOrderId(donhang.getOrderId())) {

				tblDonHang.addView(setUp(sku), new TableLayout.LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			}

		}
	}

	public void initView() {
		txt_tong_can_thu = (TextView) findViewById(R.id.txt_tong_can_thu);
		txt_create_date = (TextView) findViewById(R.id.txt_create_date);
		txt_client_name = (TextView) findViewById(R.id.txt_client_name);
		txt_client_phone = (TextView) findViewById(R.id.txt_client_phone);
		txt_client_address = (TextView) findViewById(R.id.txt_client_address);
		txt_comments = (TextView) findViewById(R.id.txt_comments);
		txt_ma_dh = (TextView) findViewById(R.id.txt_ma_dh);
		tblDonHang = (TableLayout) findViewById(R.id.tblDonHang);

		// set event for button
		// set event for button
		findViewById(R.id.btn_success).setOnClickListener(onclick);
		findViewById(R.id.btn_delay).setOnClickListener(onclick);
		findViewById(R.id.btn_nocontact).setOnClickListener(onclick);
		findViewById(R.id.btn_outofstock).setOnClickListener(onclick);
		findViewById(R.id.btn_cancel).setOnClickListener(onclick);
		findViewById(R.id.btn_call).setOnClickListener(onclick);

		/** Get the current time */
		final Calendar cal = Calendar.getInstance();
		pDay = cal.get(Calendar.DATE);
		pMonth = cal.get(Calendar.MONTH);
		pYear = cal.get(Calendar.YEAR);

	}

	public OnClickListener onclick = new OnClickListener() {

		@SuppressLint("NewApi")
		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.btn_success:

				// update status donhang
				donhang.setStatus(DH_STATUS_SUCCESS);// 7
				donhang.setStatus_trave(DH_STATUS_SUCCESS);// trang thai don
															// hang giao dich
															// thanh cong
				db.updateDonhang(donhang);

				for (SKU sku : db.getAllSKUByOrderId(donhang.getOrderId())) {

					if (sku.getSku_Quantity_Delivery() > 0) {
						// update status sku of order for reused screen report
						// sku.setSku_status(1);// status=1 delivery success
						db.updateSku(SKU_STATUS_SUCCESS,
								sku.getSku_Quantity_Delivery(),
								donhang.getOrderId(), sku.getSkuId());
					}
					if (isNetworkAvailable()) {
						new backupStatusSKU(String.valueOf(nhanvien.getId()),
								String.valueOf(donhang.getOrderId()),
								String.valueOf(donhang.getStatus()), "", "",
								sku.getSkuId() + ","
										+ sku.getSku_Quantity_Delivery() + ","
										+ option).execute();
					} else {
						donhang.setIs_Synchonize(1);
						db.updateDonhang(donhang);
						
						showToast(
								getResources().getString(
										R.string.network_unable),
								Toast.LENGTH_LONG);
					}
				}

				TabGroupActivity tab_success = (TabGroupActivity) self
						.getParent();
				tab_success.finishFromChild(DonHangDetailActivity.this);

				break;

			case R.id.btn_delay:

				myDialog = new DatePickerDialog(getParent(),
						mOnDateSetListener, pYear, pMonth, pDay);

				myDialog.setButton(DialogInterface.BUTTON_POSITIVE,
						getResources().getString(R.string.label_dong_y),
						myDialog);

				myDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
						getResources().getString(R.string.label_huy), myDialog);

				myDialog.setTitle(getResources().getString(
						R.string.label_ngay_giao)
						+ Utils.getDayOfWeek(pYear, pMonth, pDay));

				myDialog.show();

				break;

			case R.id.btn_nocontact:
				// update status donhang
				donhang.setStatus(DH_STATUS_CONTACT_FAILED);
				donhang.setStatus_trave(DH_STATUS_CONTACT_FAILED);// Trang thai
																	// don hang
																	// lien lac
																	// ko duoc
				db.updateDonhang(donhang);
				if (isNetworkAvailable()) {
					new backupStatusSKU(String.valueOf(nhanvien.getId()),
							String.valueOf(donhang.getOrderId()),
							String.valueOf(donhang.getStatus()), shipDate,
							datePart, "").execute();
				} else {
					
					donhang.setIs_Synchonize(1);
					db.updateDonhang(donhang);
					
					showToast(
							getResources().getString(R.string.network_unable),
							Toast.LENGTH_LONG);
				}
				TabGroupActivity tab_nocontact = (TabGroupActivity) self
						.getParent();
				tab_nocontact.finishFromChild(DonHangDetailActivity.this);

				break;

			case R.id.btn_outofstock:
				// update status donhang
				donhang.setStatus(DH_STATUS_WRONG_PRODUCT);
				donhang.setStatus_trave(DH_STATUS_WRONG_PRODUCT);// Trang thai
																	// don hang
																	// san pham
																	// loi
				db.updateDonhang(donhang);

				if (isNetworkAvailable()) {
					// backup don hang
					new backupStatusSKU(String.valueOf(nhanvien.getId()),
							String.valueOf(donhang.getOrderId()),
							String.valueOf(donhang.getStatus()), shipDate,
							datePart, "").execute();
				} else {
					
					donhang.setIs_Synchonize(1);
					db.updateDonhang(donhang);
					
					showToast(
							getResources().getString(R.string.network_unable),
							Toast.LENGTH_LONG);
				}
				TabGroupActivity tab_outofstock = (TabGroupActivity) self
						.getParent();
				tab_outofstock.finishFromChild(DonHangDetailActivity.this);
				break;

			case R.id.btn_cancel:

				TabGroupActivity tab_cancel = (TabGroupActivity) self
						.getParent();
				tab_cancel.finishFromChild(DonHangDetailActivity.this);

				Intent intent_khachhuy = new Intent(self, DonHangKhachHuy.class);
				Bundle bundle = new Bundle();
				bundle.putParcelable(DONHANG, donhang);
				intent_khachhuy.putExtras(bundle);
				tab_cancel.startChildActivity("DonHangKhachHuy",
						intent_khachhuy);
				break;
			case R.id.btn_call:
				// function call system here
				Intent callIntent = new Intent(Intent.ACTION_CALL);
				callIntent.setData(Uri.parse("tel:" + donhang.getPhone()));
				startActivity(callIntent);

				break;
			default:
				break;
			}
			int index = db.getAllDonHangDangGiao().size();
			BadgeTabManager.getInstance().setBadgeAtIndex(index, 0);
		}
	};

	public TableRow setUp(final SKU sku) {
		row = new TableRow(self);
		View v;
		LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		v = vi.inflate(R.layout.row_phieu, null);

		final TextView txt_price = (TextView) v.findViewById(R.id.txt_price);
		final TextView txt_name = (TextView) v.findViewById(R.id.txt_name);
		final TextView txt_can_thu = (TextView) v
				.findViewById(R.id.txt_can_thu);
		final EditText edit_soluong = (EditText) v
				.findViewById(R.id.edit_soluong);

		final LinearLayout why_change = (LinearLayout) v
				.findViewById(R.id.why_change);
		final LinearLayout root_can_thu = (LinearLayout) v
				.findViewById(R.id.root_can_thu);
		final ImageView iv_24h = (ImageView) v.findViewById(R.id.iv_24h);
		final ImageView iv_voucher = (ImageView) v
				.findViewById(R.id.iv_voucher);

		RadioGroup radioGroup = (RadioGroup) v.findViewById(R.id.radioGroup);

		// find the radiobutton by returned id
		final RadioButton radioOption1 = (RadioButton) v
				.findViewById(R.id.radioOption1);

		final RadioButton radioOption2 = (RadioButton) v
				.findViewById(R.id.radioOption2);

		final RadioButton radioOption3 = (RadioButton) v
				.findViewById(R.id.radioOption3);

		// set data for view
		txt_name.setText(sku.getSkuName());
		txt_price.setText(Utils.priceWithoutDecimal(sku.getPrice()) + "đ");

		txt_can_thu.setText((Utils.priceWithoutDecimal(sku
				.getSku_Quantity_Delivery() * sku.getPrice()))
				+ "đ");
		edit_soluong.setText(String.valueOf(sku.getSku_Quantity_Delivery()));

		// check for hide/show icon 24h
		int isVisible = donhang.getShipExpress() == 1 ? View.VISIBLE
				: View.GONE;
		iv_24h.setVisibility(isVisible);

		// check for hide/show product type
		if (sku.getProductType() == 1) {
			iv_voucher.setBackgroundResource(R.drawable.icon_voucher);
		} else {
			iv_voucher.setBackgroundResource(R.drawable.icon_vip);
		}

		final ImageButton btn_add = (ImageButton) v.findViewById(R.id.btn_add);
		final ImageButton btn_sub = (ImageButton) v.findViewById(R.id.btn_sub);

		// set tag for view
		btn_add.setTag(sku);
		btn_sub.setTag(sku);

		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if (checkedId == R.id.radioOption1) {
					Toast.makeText(self, radioOption1.getText(),
							Toast.LENGTH_LONG).show();
					option = 1;
					// backup sku for reason change quantity
					db.updateSkuWhyChange(option, donhang.getOrderId(),
							sku.getSkuId());

					// new backupStatusSKU(String.valueOf(nhanvien.getId()),
					// String.valueOf(donhang.getOrderId()), String
					// .valueOf(donhang.getStatus()), "", "", sku
					// .getSkuId() + "," + option).execute();

				} else if (checkedId == R.id.radioOption2) {
					Toast.makeText(self, radioOption2.getText(),
							Toast.LENGTH_LONG).show();

					option = 2;

					// backup sku for reason change quantity
					db.updateSkuWhyChange(option, donhang.getOrderId(),
							sku.getSkuId());

					// new backupStatusSKU(String.valueOf(nhanvien.getId()),
					// String.valueOf(donhang.getOrderId()), String
					// .valueOf(donhang.getStatus()), "", "", sku
					// .getSkuId() + "," + option).execute();
				} else {

					option = 3;

					// backup sku for reason change quantity
					db.updateSkuWhyChange(option, donhang.getOrderId(),
							sku.getSkuId());

					// new backupStatusSKU(String.valueOf(nhanvien.getId()),
					// String.valueOf(donhang.getOrderId()), String
					// .valueOf(donhang.getStatus()), "", "", sku
					// .getSkuId() + "," + option).execute();
				}

			}
		});

		// set event for button
		btn_add.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				SKU sku = (SKU) v.getTag();
				if (sku.getQuantity() > Integer.parseInt(edit_soluong.getText()
						.toString())) {
					edit_soluong.setText(String.valueOf(Integer
							.parseInt(edit_soluong.getText().toString()) + 1));
					double quantity = Double.parseDouble(edit_soluong.getText()
							.toString());
					double price = sku.getPrice();
					// price = price *1000 ;
					String a_canthu = Utils.priceWithoutDecimal(quantity
							* price)
							+ "đ";
					total_canthu += sku.getPrice();
					txt_can_thu.setText(a_canthu);

					txt_tong_can_thu.setText(Utils
							.priceWithoutDecimal(total_canthu) + "đ");
					if (Integer.parseInt(edit_soluong.getText().toString()) < sku
							.getQuantity()) {
						why_change.setVisibility(VISIBLE);
						root_can_thu.setVisibility(GONE);
					} else {
						why_change.setVisibility(GONE);
						root_can_thu.setVisibility(VISIBLE);
					}

					// update quantity sku
					updateSku(sku.getSkuId(),
							Integer.parseInt(edit_soluong.getText().toString()));
					// total_canthu+=sku.getPrice();
					db.updateTotalMoney(donhang.getOrderId(), total_canthu);
				}
			}
		});

		btn_sub.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				SKU sku = (SKU) v.getTag();
				if (Integer.parseInt(edit_soluong.getText().toString()) > 0) {
					edit_soluong.setText(String.valueOf(Integer
							.parseInt(edit_soluong.getText().toString()) - 1));
					double quantity = Double.parseDouble(edit_soluong.getText()
							.toString());
					double price = sku.getPrice();
					String a_canthu = Utils.priceWithoutDecimal(quantity
							* price)
							+ "đ";

					total_canthu -= sku.getPrice();
					txt_can_thu.setText(a_canthu);
					txt_tong_can_thu.setText(total_canthu + "đ");
					if (Integer.parseInt(edit_soluong.getText().toString()) < sku
							.getQuantity()) {
						why_change.setVisibility(VISIBLE);
					} else {
						why_change.setVisibility(INVISIBLE);
					}
					// update quantity sku
					updateSku(sku.getSkuId(),
							Integer.parseInt(edit_soluong.getText().toString()));
					// total_canthu-=sku.getPrice();
					db.updateTotalMoney(donhang.getOrderId(), total_canthu);
				}
			}
		});

		row.addView(v);
		return row;
	}

	public void updateSku(int skuId, int quantity) {
		db.updateSku(Utils.SKU_STATUS_CANCEL, quantity, donhang.getOrderId(),
				skuId);

	}

	public class backupStatusSKU extends AsyncTask<Void, Void, Integer> {

		private String user_id;
		private String order_id;
		private String status;
		private String ship_date;
		private String date_part;
		private String sku;

		public backupStatusSKU(String user_id, String order_id, String status,
				String ship_date, String date_part, String sku) {
			this.user_id = user_id;
			this.order_id = order_id;
			this.status = status;
			this.ship_date = ship_date;
			this.date_part = date_part;
			this.sku = sku;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Integer doInBackground(Void... params) {
			try {
				String json = CallServices.BackupSigleOrder(self, user_id,
						order_id, status, ship_date, date_part, sku);

				if (json != null) {
					json = "{\"backup\":" + json + "}";
					JSONObject obj = new JSONObject(json);
					JSONObject arr = obj.getJSONObject("backup");
					int counter = Integer.parseInt(arr.getString("Code"));
					return counter;
				}

			} catch (Exception e) {
				// TODO: handle exception
			}
			// WriteLog.d(TAG, json);
			// backup faild
			return 1;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result == 0) {
				// update status synchonize to server here
				donhang.setIs_Synchonize(0);
				db.updateDonhang(donhang);

			}else{
				// update status synchonize to server here
				donhang.setIs_Synchonize(1);
				db.updateDonhang(donhang);
			}
		}

	}

	private DatePickerDialog.OnDateSetListener mOnDateSetListener = new OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker arg0, int year, int month, int day) {

			shipDate = month + "/" + day + "/" + year;
			Dialog dialog = onCreateDialogSingleChoice();
			dialog.show();
			//
			// Dialog dialog = new Toast.makeText(getApplicationContext(), arg1
			// + "-" + "" + arg2 + "-" + arg3, Toast.LENGTH_LONG).show();
		}

	};

	public Dialog onCreateDialogSingleChoice() {

		// Initialize the Alert Dialog
		AlertDialog.Builder builder = new AlertDialog.Builder(getParent());
		// Source of the data in the DIalog

		// Set the dialog title
		builder.setTitle(
				getResources().getString(R.string.label_thoi_gian_giao))
				// Specify the list array, the items to be selected by default
				// (null for none),
				// and the listener through which to receive callbacks when
				// items are selected
				.setSingleChoiceItems(myList, 0,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								switch (which) {
								case 0:
									datePart = "1";
									break;
								case 1:
									datePart = "2";
									break;
								case 2:
									datePart = "3";
									break;

								default:
									break;
								}

							}
						})

				// Set the action buttons
				.setPositiveButton(
						getResources().getString(R.string.label_dong_y),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								// User clicked OK, so save the result somewhere
								// or return them to the component that opened
								// the dialog

								// update status donhang
								donhang.setStatus(DH_STATUS_DELAY);
								donhang.setStatus_trave(DH_STATUS_DELAY);
								db.updateDonhang(donhang);

								// Toast.makeText(getParent(),
								// datePart+"========="+shipDate,
								// Toast.LENGTH_LONG).show();

								if (isNetworkAvailable()) {
									new backupStatusSKU(String.valueOf(nhanvien
											.getId()), String.valueOf(donhang
											.getOrderId()), String
											.valueOf(donhang.getStatus()),
											shipDate, datePart, "").execute();

								} else {
									showToast(
											getResources().getString(
													R.string.network_unable),
											Toast.LENGTH_LONG);
								}

								TabGroupActivity tab_delay = (TabGroupActivity) self
										.getParent();
								tab_delay
										.finishFromChild(DonHangDetailActivity.this);

							}
						})
				.setNegativeButton(
						getResources().getString(R.string.label_huy),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {

							}
						});

		return builder.create();
	}

	@Override
	public void onDateChanged(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		Toast.makeText(getApplicationContext(), "hahahahah", Toast.LENGTH_LONG)
				.show();

	}

}
